package com.goambu.driver.autenticacion.controller;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

import com.goambu.driver.GoAmbuDriverApp;
import com.goambu.driver.GoAmbuDriverConstants;
import com.goambu.driver.autenticacion.entities.AlertaBean;
import com.goambu.driver.autenticacion.entities.SessionBean;
import com.goambu.driver.autenticacion.entities.UsuarioBean;
import com.goambu.driver.autenticacion.entities.WorkerBean;
import com.goambu.driver.autenticacion.model.GetWorkerResponse;
import com.goambu.driver.autenticacion.model.LoginResponse;
import com.goambu.driver.autenticacion.model.PutWorkerUpdateResponse;
import com.goambu.driver.autenticacion.view.AlertaFragment;
import com.goambu.driver.autenticacion.view.AlertaPopup;
import com.goambu.driver.autenticacion.view.CentroMedicoPopup;
import com.goambu.driver.autenticacion.view.MainActivity;
import com.goambu.driver.framework.controller.internet.HttpConnector;
import com.google.android.gms.wearable.Channel.GetOutputStreamResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class AutenticacionController {
	public static AutenticacionController instance = null;
	public UsuarioBean currentUser = null;
	public static final String SHARED_USERNAME = "username";
	public static final String SHARED_PASSWORD = "password";
	public static final String SHARED_NOTIFICATIONFLAG = "notifflag";
	public static final String REG_ID = "regId";
	public static final String EMAIL_ID = "eMailId";
	LoginResponse loginResponse = new LoginResponse();

	SharedPreferences pref;
	Editor editor;

	public AutenticacionController() {
		pref = GoAmbuDriverApp.context.getSharedPreferences("GoAmbuDriver",
				Context.MODE_PRIVATE); // 0 - for private mode
	}

	public static AutenticacionController getInstance() {
		if (instance == null) {
			instance = new AutenticacionController();
		}
		return instance;
	}

	public String getRegistrationId() {
		return pref.getString(REG_ID, "");
	}

	public SessionBean getSession() {
		String txtUser, txtPass;
		SessionBean session = new SessionBean();

		txtUser = pref.getString(SHARED_USERNAME, "");
		txtPass = pref.getString(SHARED_PASSWORD, "");

		session.username = txtUser;
		session.password = txtPass;

		return session;
	}

	/**
	 * Create login session
	 * */
	public void createLoginSession(String username, String password) {
		editor = pref.edit();
		// Storing username value
		editor.putString(SHARED_USERNAME, username);

		// Storing password in pref
		editor.putString(SHARED_PASSWORD, password);

		// commit changes
		editor.commit();
	}
	
	public void saveNotificationFlag(int flag) {
		editor = pref.edit();
		// Storing notification value
		editor.putInt(SHARED_NOTIFICATIONFLAG, flag);
		// commit changes
		editor.commit();
	}
	
	public int getNotificationFlag() {
		return pref.getInt(SHARED_NOTIFICATIONFLAG, 0); 
	}

	public void logoutSession() {
		editor = pref.edit();
		editor.putString(SHARED_USERNAME, "");
		editor.putString(SHARED_PASSWORD, "");
		editor.putInt(SHARED_NOTIFICATIONFLAG, 0);
		editor.commit();
		AutenticacionController.getInstance().currentUser = null;
		AmbulanciaController.getInstance().thisLocation = null;
	}

	public void storeRegIdinSharedPref(String regId) {
		editor = pref.edit();
		editor.putString(REG_ID, regId);
		// editor.putString(EMAIL_ID, emailID);
		editor.commit();
	}

	public LoginResponse getLoginResponse(String username, String password) {
		limpiarVariables();

		String path = GoAmbuDriverConstants.SERVER_URL
				+ GoAmbuDriverConstants.AUTENTICACION_GETLOGIN;

		Gson gs = new Gson();
		String strResponse;
		LoginResponse objResponse = null;

		JSONObject parametros = new JSONObject();
		try {
			parametros.put("username", username);
			parametros.put("password", password);
			// parametros.put("username", "b.carranza@pucp.pe");
			// parametros.put("password", "NTi3nvih");
		} catch (JSONException e) {
			e.printStackTrace();
		}

		HttpResponse respuesta = HttpConnector.makeRequest(path,
				parametros.toString());

		if (respuesta != null) {
			try {
				strResponse = EntityUtils.toString(respuesta.getEntity());
				objResponse = gs.fromJson(strResponse, LoginResponse.class);

			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				currentUser = null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				currentUser = null;
			}
		}

		if (objResponse != null) {
			if (!objResponse.id.isEmpty()) {
				currentUser = new UsuarioBean();
				currentUser.userid = objResponse.id;
				currentUser.username = objResponse.username;
				currentUser.currentStatus = objResponse.currentStatus;
				currentUser.salt = objResponse.salt;
				currentUser.roleId = objResponse.roleId;
				objResponse.workerResponse = getWorkerByID(currentUser.userid);
				CentrosMedicosController.getInstance().getCentrosMedicosByOrg();
			} else
				currentUser = null;
		} else
			currentUser = null;

		return objResponse;

	}

	public GetWorkerResponse getWorkerByUser(String userid) {
		String path = String
				.format("http://54.200.75.79:8080/goambu/api/organizations/1/workers?user_id=%s",
						userid);

		Gson gs = new Gson();
		String strResponse;
		ArrayList<GetWorkerResponse> objResponse = null;
		WorkerBean worker = currentUser.worker;
		GetWorkerResponse tmp = null;

		HttpResponse respuesta = HttpConnector.makeGetRequest(path, "");

		if (respuesta != null) {
			try {
				strResponse = EntityUtils.toString(respuesta.getEntity());
				Type listType = new TypeToken<ArrayList<GetWorkerResponse>>() {
				}.getType();
				objResponse = gs.fromJson(strResponse, listType);

			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				worker = null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				worker = null;
			}
		}

		if (objResponse != null) {
			if (objResponse.size() > 0) {
				for (int i = 0; i < objResponse.size(); i++) {
					tmp = objResponse.get(i);
					worker = new WorkerBean();
					worker.workerid = tmp.id;
					worker.nin = tmp.nin;
					worker.firstName = tmp.firstName;
					worker.lastName = tmp.lastName;
					worker.mobile = tmp.mobile;
					worker.mobilePlatform = tmp.mobilePlatform;
					worker.email = tmp.email;
					worker.currentStatus = tmp.currentStatus;
					worker.workerType = tmp.workerType;
					worker.organizationId = tmp.organizationId;
					currentUser.worker = worker;
					AmbulanciaController.getInstance().GetEmergencyUnit(
							currentUser);

				}

			} else
				worker = null;
		} else
			worker = null;

		return tmp;
	}

	public GetWorkerResponse getWorkerByID(String userid) {
	/*	if (1 == 1) {
			return getWorkerByUser(userid);
		}*/

		String path = GoAmbuDriverConstants.SERVER_URL
				+ String.format(
						GoAmbuDriverConstants.AUTENTICACION_GETWORKERBYID,
						userid);

		Gson gs = new Gson();
		String strResponse;
		GetWorkerResponse objResponse = null;
		WorkerBean worker = currentUser.worker;

		HttpResponse respuesta = HttpConnector.makeGetRequest(path, "");

		if (respuesta != null) {
			try {
				strResponse = EntityUtils.toString(respuesta.getEntity());
				objResponse = gs.fromJson(strResponse, GetWorkerResponse.class);

			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				worker = null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				worker = null;
			}
		}

		if (objResponse != null) {
			if (!objResponse.id.isEmpty()) {
				worker = new WorkerBean();
				worker.workerid = objResponse.id;
				worker.nin = objResponse.nin;
				worker.firstName = objResponse.firstName;
				worker.lastName = objResponse.lastName;
				worker.mobile = objResponse.mobile;
				worker.mobilePlatform = objResponse.mobilePlatform;
				worker.email = objResponse.email;
				worker.currentStatus = objResponse.currentStatus;
				worker.workerType = objResponse.workerType;
				worker.organizationId = objResponse.organizationId;
				currentUser.worker = worker;
				objResponse.emergencyunitResponse = AmbulanciaController
						.getInstance().GetEmergencyUnit(currentUser);
			} else
				worker = null;
		} else
			worker = null;

		return objResponse;
	}

	public PutWorkerUpdateResponse UpdateWorkerNotificationToken(
			String notificationId) {
		if (currentUser == null) {
			return null;
		} else if (currentUser.worker == null) {
			return null;
		}
		UsuarioBean currentUser = AutenticacionController.getInstance().currentUser;
		String path = GoAmbuDriverConstants.SERVER_URL
				+ String.format(
						GoAmbuDriverConstants.AUTENTICACION_UPDATEWOKERPUSHNOTIF,
						currentUser.worker.organizationId,
						currentUser.worker.workerid);

		Gson gs = new Gson();
		String strResponse;
		PutWorkerUpdateResponse objResponse = null;

		JSONObject parametros = new JSONObject();

		try {
			parametros.put("id", currentUser.worker.workerid);
			parametros.put("nin", currentUser.worker.nin);
			parametros.put("firstName", currentUser.worker.firstName);
			parametros.put("lastName", currentUser.worker.lastName);
			parametros.put("email", currentUser.worker.email);
			parametros.put("mobile", currentUser.worker.mobile);
			parametros.put("mobilePlatform", currentUser.worker.mobilePlatform);
			parametros.put("workerType", currentUser.worker.workerType);
			parametros.put("currentStatus", currentUser.worker.currentStatus);
			parametros.put("userId", currentUser.worker.userId);
			parametros.put("notificationToken", notificationId);
			parametros.put("organizationId", currentUser.worker.organizationId);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		Log.d("UpdateWorkerNotificationTokenPath", path);
		Log.d("UpdateWorkerNotificationTokenParam", parametros.toString());
		HttpResponse respuesta = HttpConnector.makePutRequest(path,
				parametros.toString());

		/*
		 * if (respuesta != null) { try { strResponse =
		 * EntityUtils.toString(respuesta.getEntity()); objResponse =
		 * gs.fromJson(strResponse, PutWorkerUpdateResponse.class); } catch
		 * (ParseException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated
		 * catch block e.printStackTrace(); } }
		 */
		return objResponse;

	}

	private static void limpiarVariables() {
		AutenticacionController.getInstance().currentUser = null;
	}

}
